package workexp.zookeeper;


import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"rawtypes","unchecked"})
public class ZkPool {
	
	private static final Logger logger = LoggerFactory.getLogger(ZkPool.class);
	
	private static GenericObjectPool pool;
	
	public static GenericObjectPool getPool() {
		return pool;
	}

	public static void setPool(GenericObjectPool pool) {
		ZkPool.pool = pool;
	}

	public static GenericObjectPool initPool(GenericObjectPoolConfig conf) {
		/*
		conf.setMaxTotal(100); // 能从池中借出的对象的最大数目  
		conf.setMaxIdle(10); // 池中可以空闲对象的最大数目  
		conf.setMaxWaitMillis(10000); // 对象池空时调用borrowObject方法，最多等待多少毫秒  
		conf.setTimeBetweenEvictionRunsMillis(600000);// 间隔每过多少毫秒进行一次后台对象清理的行动  
		conf.setNumTestsPerEvictionRun(-1);// －1表示清理时检查所有线程  
		conf.setMinEvictableIdleTimeMillis(3000);// 设定在进行后台对象清理时，休眠时间超过了3000毫秒
		*/
		if(pool == null){
			pool = new GenericObjectPool(new ZkClientFactory(), conf);
		}
		
		logger.info("init iuap zklock rootpath success!");
		logger.info("active num is " + pool.getNumActive());
		
		return pool;
		
	}

	/**
	 * 池中取出对象
	 */
	public static CuratorFramework getClient() {
		CuratorFramework obj = null;
		try {
			obj = (CuratorFramework) pool.borrowObject();
			logger.info("从池中获取CuratorFramework对象成功!");
		} catch (Exception e) {
			logger.error("get client from zkpool error!", e);
		}
		return obj;
	}

	/**
	 * 对象放回池中
	 */
	public static boolean returnClient(Object obj) {
		try {
			pool.returnObject(obj);
			logger.info("向池中归还CuratorFramework对象成功!");
		} catch (Exception e) {
			logger.error("向池中归还CuratorFramework对象失败!", e);
			return false;
		}
		return true;
	}
	
	/**
	 * 将失效对象放回池中
	 * 
	 * @throws Exception 
	 */
	public static void returnBrokenClient(Object obj) {
		if (obj != null) {
			try {
				pool.invalidateObject(obj);
				logger.info("向池中归还失效的CuratorFramework对象成功!");
			} catch (Exception e) {
				logger.error("向池中归还失效的CuratorFramework对象失败!!",e);
			}
		}
	}
}
